package com.yun.mult;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created by lsy
 * on 2020/11/26 18:08.
 */
public class ThreeThreadJoin {
    // 有三个任务，a耗时2s，b耗时1.1秒，c耗时1秒。c依赖于b的结果
    // 多线程并行计算一下
    public static void main(String[] args) throws InterruptedException {
        // 几个依赖任务 ，2个
        List<List<String>> list = new ArrayList<>();
        list.add(new ArrayList<>(Arrays.asList("taskA")));
        list.add(new ArrayList<>(Arrays.asList("taskB","taskC")));

        ThreeThreadJoin instance = new ThreeThreadJoin();

        CountDownLatch countDownLatch = new CountDownLatch(2);

        for (List<String> methods : list) {
            new Thread(() -> {

                for (String method : methods) {
                    // 多次开始，找到方法实现类
                    try {
                        Method instanceMethod = ThreeThreadJoin.class.getDeclaredMethod(method);
                        instanceMethod.invoke(instance);

                    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
                countDownLatch.countDown();
            }).start();
        }

        countDownLatch.await();
        System.out.println("主线程ok");

    }


    public void taskA() throws InterruptedException {
        System.out.println("taskA start");
        Thread.sleep(2000);
        System.out.println("taskA over");
    }
    public void taskB() throws InterruptedException {
        System.out.println("taskB start");
        Thread.sleep(1100);
        System.out.println("taskB over");
    }
    public void taskC() throws InterruptedException {
        System.out.println("taskC start");
        Thread.sleep(1000);
        System.out.println("taskC over");
    }
}
